<template>
  <ArtTableFullScreen>
    <div id="table-full-screen">
      <el-card shadow="never" class="art-table-card">
        <ArtTableHeader
          :columnList="columnOptions"
          v-model:columns="columnChecks"
          @refresh="handleRefresh"
        >
          <template #left>
            <el-button @click="showDialog('add')" :icon="Plus" v-ripple>新增</el-button>
          </template>
        </ArtTableHeader>
        <art-table
          :data="tableData"
          :loading="loading"
          :currentPage="queryParams.page"
          :pageSize="queryParams.size"
          :total="total"
          @size-change="getTableData"
          @current-change="getTableData"
        >
          <template #default>
            <el-table-column v-for="col in columns" :key="col.prop" v-bind="col" />
          </template>
        </art-table>

        <el-dialog
          v-model="dialogVisible"
          :title="dialogType === 'add' ? '新增banner' : '修改baner'"
          width="40%"
        >
          <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
            <el-form-item label="标题" prop="title">
              <el-input v-model="formData.title" placeholder="请输入活动标题" />
            </el-form-item>
            <el-form-item label="链接" prop="url">
              <el-input
                v-model="formData.url"
                placeholder="请输入链接地址"
                class="input-with-select"
              >
                <template #prepend>
                  <el-select v-model="myRoutes" style="width: 115px">
                    <el-option
                      v-for="(item, index) in restaurants"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="封面" prop="cover">
              <ArtImageUpload v-model:files="formData.cover"></ArtImageUpload>
            </el-form-item>
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="formData.sort" :min="1" />
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="handleSubmit">提交</el-button>
            </div>
          </template>
        </el-dialog>
      </el-card>
      <Annex ref="annexRef" :type="1"></Annex>
    </div>
  </ArtTableFullScreen>
</template>

<script setup lang="ts">
  import { h } from 'vue'
  import { FormInstance } from 'element-plus'
  import { ElMessageBox, ElMessage, ElButton } from 'element-plus'
  import type { FormRules } from 'element-plus'
  import { ContentService } from '@/api/common'
  import { FormParams } from '@/types/form-query'
  import { Plus, Delete, Edit, Document } from '@element-plus/icons-vue'
  import { useCheckedColumns } from '@/composables/useCheckedColumns'
  import ArtImagePreview from '@/components/image/ArtImagePreview.vue'

  const dialogType = ref('add')
  const dialogVisible = ref(false)
  const loading = ref(false)
  const total = ref(0)
  const tableData = ref<any>([])
  const annexRef = ref(null)

  const formData = reactive<FormParams>({
    url: '',
    cover: '',
    title: '',
    sort: 10,
    cate_id: 29
  })

  const myRoutes = 'https://'

  const restaurants = reactive([
    { label: '本地', value: 'com.hn.qingnai.ui.activity.' },
    { label: '自定义', value: '自定义' }
  ])

  const queryParams = reactive({
    page: 1,
    size: 10,
    cate_id: 29
  })
  // 列配置
  const columnOptions = [
    { label: 'ID', prop: 'id' },
    { label: '标题', prop: 'title' },
    { label: '链接', prop: 'url' },
    { label: '封面', prop: 'cover' },
    { label: '排序', prop: 'sort' },
    { label: '创建日期', prop: 'create_time' },
    { label: '操作', prop: 'operation' }
  ]

  // 动态列配置
  const { columnChecks, columns } = useCheckedColumns(() => [
    { type: 'index', label: '序号', align: 'center', width: 80 }, // 序号列
    { prop: 'id', label: 'ID', align: 'center' },
    { prop: 'title', label: '标题', align: 'center' },
    { prop: 'url', label: '链接', align: 'center', showOverflowTooltip: true },
    {
      prop: 'cover',
      label: '封面',
      align: 'center',
      formatter: (row: any) => {
        return h(ArtImagePreview, { src: row.cover })
      }
    },
    {
      prop: 'create_time',
      label: '创建日期',
      sortable: true,
      align: 'center'
    },
    {
      prop: 'operation',
      label: '操作',
      width: 220,
      align: 'center',
      fixed: 'right', // 固定在右侧
      formatter: (row: any) => {
        return h('div', { class: 'option' }, [
          h(
            ElButton,
            {
              size: 'small',
              icon: Edit,
              text: true,
              onClick: () => showDialog('edit', row)
            },
            () => '编辑'
          ),
          h(
            ElButton,
            {
              size: 'small',
              type: 'danger',
              icon: Delete,
              text: true,
              onClick: () => deleteTableRow(row)
            },
            () => '删除'
          ),
          h(
            ElButton,
            {
              size: 'small',
              icon: Document,
              text: true,
              onClick: () => showAnnex(row)
            },
            () => '附件'
          )
        ])
      }
    }
  ])

  onMounted(() => {
    getTableData()
  })

  const handleRefresh = () => {
    getTableData()
  }
  // 获取商品列表
  const getTableData = async () => {
    loading.value = true
    const res = await ContentService.getListContent(queryParams)
    total.value = res.data.total
    tableData.value = res.data.data
    loading.value = false
  }

  // 显示附件弹窗
  const showAnnex = (row: any) => {
    annexRef.value.openList(row.id, row.cover)
  }

  const showDialog = (type: string, row?: any) => {
    if (type === 'edit' && row) {
      formData.url = row.url !== null ? row.url.replace(myRoutes, '') : ''
      formData.cover = row.cover
      formData.title = row.title
      formData.sort = row.sort
      formData.id = row.id
    } else {
      formData.url = ''
      formData.title = ''
      formData.cover = ''
      formData.sort = 10
      formData.id = ''
    }
    dialogVisible.value = true
    dialogType.value = type
  }

  const deleteTableRow = (row: any) => {
    ElMessageBox.confirm('确定要删除该banber吗？', '删除banner', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    })
      .then(() => {
        return ContentService.deleteContent(row.id)
      })
      .then(() => {
        getTableData()
        ElMessage.success('删除成功')
      })
  }

  const rules = reactive<FormRules>({
    url: [{ required: true, message: '请输入链接', trigger: 'blur' }],
    cover: [{ required: true, message: '请选择封面', trigger: 'blur' }],
    title: [{ required: true, message: '请输入标题', trigger: 'blur' }]
  })

  const formRef = ref<FormInstance>()

  const handleSubmit = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid) => {
      if (valid) {
        if (dialogType.value === 'add') {
          await ContentService.addContent(formData)
        } else {
          await ContentService.updateContent(formData)
        }
        ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
        await getTableData()
        dialogVisible.value = false
      }
    })
  }
</script>

<style lang="scss" scoped>
  :deep(.option .el-button + .el-button) {
    margin-left: 0;
  }
</style>
